package com.zzedu.aop;

import com.zzedu.annon.AccessPermission;
import com.zzedu.common.enums.UserTypeEnumns;
import com.zzedu.common.utils.SecurityUtils;
import com.zzedu.common.utils.security.LoginUser;
import com.zzedu.service.IZzSchoolService;
import com.zzedu.service.IZzStudentService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 访问权限验证
 */
@Aspect
@Component
public class AccessPermissionAspect {

    Logger logger = LoggerFactory.getLogger(AccessPermissionAspect.class);
    @Autowired
    IZzSchoolService zzSchoolService;

    @Autowired
    IZzStudentService zzStudentService;

    @Pointcut("@annotation(com.zzedu.annon.AccessPermission) || @within(com.zzedu.annon.AccessPermission)")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (null != loginUser) {
                Class<?> targetClass = joinPoint.getTarget().getClass();
                AccessPermission accessPermission = AnnotationUtils.findAnnotation(targetClass,AccessPermission.class);
                if(null==accessPermission){
                    // 1. 获取被拦截的方法的 Signature
                    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                    Method method = signature.getMethod();
                    accessPermission = AnnotationUtils.findAnnotation(method,AccessPermission.class);
                }
                if(null!=accessPermission){
                    UserTypeEnumns[] userTypeEnumns = accessPermission.value();
                    if(null!=userTypeEnumns){
                        boolean isRight=false;
                        for(UserTypeEnumns typeEnumns:userTypeEnumns){
                            if(typeEnumns==loginUser.getUserTypeEnumns()){
                                isRight = true;
                                break;
                            }
                        }
                        if(!isRight){
                            throw new AccessDeniedException("无此服务访问权限");
                        }
                    }
                }
            }

    }
}
